//
//  LogVIewController.m
//  Seizure
//
//  Created by student on 3/23/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#import "LogVIewController.h"
#import "EventLog.h"
#import "DataManager.h"
#import "EventLogDetailsViewController.h"

@implementation LogViewController

@synthesize eventLogs;
@synthesize table;
@synthesize selectedEvent;

typedef enum{
    GET_PATIENT_LOGS
} requestTypes;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    eventLogs = [[NSMutableArray alloc] init];
    if (self) {
        //Custom initialization
        NSArray *localEvents = [[DataManager sharedInstance]getLocalLogs];
        if( localEvents != nil )
        {
            [eventLogs addObjectsFromArray:localEvents];
        }
        
        [[DataManager sharedInstance] getPatientEventLogs:self requestType:GET_PATIENT_LOGS];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:NO];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


//
// This will hide the navigation bar when the back button is pressed
-(void) viewWillDisappear:(BOOL)animated {
    
    
    // back button was pressed.  We know this is true because self is no longer
    // in the navigation stack. 
    if ([self.navigationController.viewControllers indexOfObject:self]==NSNotFound) {
        
        [self.navigationController setNavigationBarHidden:YES animated:YES];
    }
    [super viewWillDisappear:animated];
}


#pragma mark -- NETWORK DATA
/**
 *  dataObject should be a NSArray
 */
//TODO: Check if there are more events in local logs than DB. If there are, submit the correct log(s) that
//          isn't in DB and enter it.
- (void)DataArrived:(id)dataObject requestType:(int)rtype
{
    if( rtype == GET_PATIENT_LOGS )
    {   
        NSArray *dataObj = (NSArray*)dataObject;
        
        if( [dataObj count] == [eventLogs count] )
            return;
        else if( [dataObj count] > [eventLogs count] )
        {
//            NSLog(@"Data Arrived in Log View Controller");
            [eventLogs removeAllObjects];
            [eventLogs addObjectsFromArray:(NSArray *)dataObject];
        
            // refresh the table  from the main queue/thread instead of the NSOperation from DBCommunicator
            // http://stackoverflow.com/a/8146782/121654 , otherwise table doesn't reload instantly
            dispatch_async(dispatch_get_main_queue(), ^(void) {
                [table reloadData];
            });
            
            [[DataManager sharedInstance]archiveLocalLogs:eventLogs];
        }
        else
        {
            DataManager *dm = [DataManager sharedInstance];
            int j = [eventLogs count] - [dataObj count];
            for(int i=0; i<j; i++)
            {
                [dm addPatientEventLogWithoutLocal:[eventLogs objectAtIndex:i]];
            }
        }
    }
}


#pragma mark -- TABLE DATA SOURCE METHODS
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"ReusableCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ReusableCell"];
    if( cell == nil )
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle  reuseIdentifier:identifier];
    }
    else {
        // clean old cell if nessecary
    }
    
    //Get the event log for this cell
    EventLog *logForCell = [eventLogs objectAtIndex:indexPath.row];
        
    NSString *formattedDate = [NSDateFormatter localizedStringFromDate:logForCell.startTime dateStyle:NSDateFormatterLongStyle timeStyle:NSDateFormatterShortStyle];
    
    int timeDistance = logForCell.startTime.timeIntervalSinceNow * -1;
    int seconds = (int)timeDistance % 60;
    int minutes = timeDistance / 60;
    int hours = timeDistance / 60 / 60;
    int days = timeDistance / 60 / 60 / 24;
    NSString *timeDiscriptor;
    
    if (days > 0)
        timeDiscriptor = days == 1 ? [NSString stringWithFormat:@"%d day ago", days] : [NSString stringWithFormat:@"%d days ago", days];
    else if (hours > 0)
        timeDiscriptor = hours == 1 ? [NSString stringWithFormat:@"%d hour ago", hours] : [NSString stringWithFormat:@"%d hours ago", hours];
    else if (minutes > 0)
        timeDiscriptor = minutes == 1 ? [NSString stringWithFormat:@"%d minute ago", minutes] : [NSString stringWithFormat:@"%d minutes ago", minutes];
    else
        timeDiscriptor = [NSString stringWithFormat:@"%d seconds ago", seconds];
    
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.textLabel.text = formattedDate;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"Recorded %@",timeDiscriptor];
    
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return eventLogs.count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    selectedEvent = [eventLogs objectAtIndex:indexPath.row];
    EventLogDetailsViewController *details = [[EventLogDetailsViewController alloc] initWithNibName:@"EventLogDetailsViewController" bundle:nil forEvent:selectedEvent];
    [table deselectRowAtIndexPath:indexPath animated:YES];
    [self.navigationController pushViewController:details animated:YES];
}

@end
